import { Button, Form, Input, Switch, useFormApi } from '@douyinfe/semi-ui';
import { useEffect, useMemo, useRef, useState } from 'react';
import { debounce } from 'lodash';
import { useNavigate } from 'react-router-dom';
import { useStoreContext } from '../dictionary-context';
import * as yup from 'yup';
import { dictionaryTypes } from '../dictionary-helper';

const schema = yup.object({});

const DictionaryEdit = ({
  entity,
  persistEntity,
  formApiRef,
}: {
  entity?: any;
  persistEntity?: (entity: any) => void;
  formApiRef?: any;
}) => {
  const { Option } = Form.Select;
  const {
    state: { dictionary },
    useDispatch,
  } = useStoreContext();
  const navigate = useNavigate();
  const { key, loading, entities } = dictionary;

  const validate = async (values: any) => {
    try {
      await schema.validate(values, { strict: true, abortEarly: false });
    } catch (err: any) {
      return err.inner.reduce(
        (pre: any, cur: any) => ({ ...pre, [cur.path]: cur.message }),
        {}
      );
    }
  };

  return (
    <Form
      getFormApi={(api: any) => {
        if (formApiRef) {
          formApiRef.current = api;
        }
      }}
      // layout='horizontal'
      // onChange={(e) => {}}
      validateFields={validate}
      onSubmit={(values: any) => {
        persistEntity && persistEntity(values);
      }}
      initValues={entity}
      onReset={() => {}}
    >
      <Form.Select
        field='dictionaryType'
        label='字典分类'
        placeholder='请选择'
        trigger='blur'
        showClear
        style={{ width: '100%' }}
        disabled={entity?.id}
      >
        {Object.values(dictionaryTypes).map((type: any) => (
          <Option key={type.value} value={type.value}>
            {type.text}
          </Option>
        ))}
      </Form.Select>
      <Form.Input
        label='字典值'
        field='dictionaryKey'
        trigger='blur'
        placeholder='请输入'
      ></Form.Input>
      <Form.Input
        label='字典名称'
        field='dictionaryName'
        trigger='blur'
        placeholder='请输入'
      ></Form.Input>
      <Form.Input
        label='字典属性'
        field='dictionaryValue'
        trigger='blur'
        placeholder='请输入'
      ></Form.Input>
      <div className='w-full flex justify-end items-center py-4 '>
        <Button onClick={() => navigate(-1)}>取消</Button>
        <Button
          theme='solid'
          htmlType='submit'
          className='mx-2'
          disabled={loading}
        >
          保存
        </Button>
      </div>
    </Form>
  );
};

export default DictionaryEdit;
